<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
  <!--<script src="js/eruda.js"></script>-->
  <script src="face-api.js"></script>
  <script src="js/commons.js"></script>
  <script src="js/faceDetectionControls.js"></script>
  <link rel="stylesheet" href="styles.css?v=2">
  <link rel="stylesheet" href="animate.min.css">
  <link rel="stylesheet" href="js/materialize.css">
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://cdn.bootcss.com/html2canvas/0.4.1/html2canvas.js"></script> 
  <script src="js/materialize.min.js"></script>
  <title>吹气球小游戏</title>
</head>
<body>
    <style>
    .loading_box {
        position: fixed;
        
        top: 0;
        
        bottom: 0;
        
        left: 0;
        
        right: 0;
        
        display: flex;
        
        justify-content: center;
        
        align-items: center;
        
        background: rgba(255 255 255 / 40%);;
        background-image: url(image/bg.png);
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: 0 200px;
        z-index: 100000;
        
    }
    .loading{
        position: absolute;
        
    }
    .loading_box .img_load{
        display: block;
        
        width:50px;
        
        height: 50px;
        margin: 0 auto;
        animation: rotating 1s linear infinite;
        
    }
    .game{
        position: relative;
        width: 100%;
        overflow: hidden;
        height: 100%;
    }
    #inputVideo{
        height: 100%;
        transform: rotateY(180deg);
        margin-left: -150px;
    }
    #overlay{
        height: 100%;
        transform: rotateY(180deg);
    }
    .play{
        position: absolute;
        bottom: 50px;
        width: 100%;
    }
    .play_start{
        padding:10px;
        margin: 0 auto;
        background: #ca19d6;
        opacity: .8;
        border-radius: 10px;
        color:#fff;
        text-align: center;
        margin: 0 auto;
        font-size: 19px;
        font-weight: bold;
        width: 100px;
        border: 1px #000 solid;
        box-shadow: 0px 1px 3px 0px black;
        height: 100px;
        border-radius: 50px;
        line-height: 79px;
    }
    .ballBg{
        position: absolute;
        top:350px;
        left: 20px;
        width: 60px;
        height: 60px;
        border-radius: 10px;
        background: #ca19d6;
        line-height: 85px;
        vertical-align:middle;
        text-align: center;
        border: 1px #000 solid;
        box-shadow: 0px 1px 3px 0px black;
        display: none;
    }
    .hongbao{
        position: absolute;
        top:65px;
    }
    .ballBg img{
        width: 35px;
        height: 35px;
    }
    .bombTotal{
        position: absolute;
        width: 100%;
        top: 50px;
        display: none;
    }
    .totalNum{
        margin: 0 auto;
        font-size: 45px;
        font-weight: bold;
        color: #fff;
        width: 50px;
        text-align: center;
        text-shadow:
           -1px -1px 0 #ca19d6,  
           1px -1px 0 #ca19d6,
           -1px 1px 0 #ca19d6,
           1px 1px 0 #ca19d6,
           0px 2px 2px rgba(0,0,0,0.6);
    }
    .limitTime{
        position: absolute;
        width: 100%;
        top: 15px;
        display: none;
    }
    .leftTime{
        margin: 0 auto;
        font-size: 35px;
        font-weight: bold;
        color: #fff;
        width: 100px;
        text-align: center;
        letter-spacing:3px;
        text-shadow:
           -1px -1px 0 #ca19d6,  
           1px -1px 0 #ca19d6,
           -1px 1px 0 #ca19d6,
           1px 1px 0 #ca19d6,
           0px 2px 2px rgba(0,0,0,0.6);
    }
    .play_end{
        position: absolute;
        top: 30px;
        width: 100%;
        display: none;
        
    }
    .play_end .result{
        margin: 0 auto;
        position: relative;
        width: 185px;
        background: #ee6ff7;
        border-radius: 10px;
        border: 5px #b353e4 solid;
        text-align: center;
        padding: 10px 5px;
        line-height: 45px;
        font-size: 17px;
        font-weight: bold;
        color: #fff;
        text-shadow: -1px -1px 0 #ca19d6, 1px -1px 0 #ca19d6, -1px 1px 0 #ca19d6, 1px 1px 0 #ca19d6, 0px 2px 2px rgba(0,0,0,0.6);
    }
    .play_end .result .title{
        width: 100px;
        margin: 0 auto;
        margin-top: -32px;
        background: #f77c25;
        border-radius: 5px;
        border: 1px solid #000;
        text-shadow: none;
    }
    .play_end .main .total{
        font-size: 25px;
        color: #fafd38;
    }
    @keyframes rotating {
        from { transform: rotate(0deg) } to { transform: rotate(360deg) }
        
    }
    </style>
    <div class="loading_box">
        <div style="position:absolute;top:30px;text-align:center">
            <a href="https://click.meituan.com/t?t=1&c=1&p=OWMpZ-uzIFOVe6JyOONs3dAc7lP6u9DWmnR1PpT24IplhVkYCqlp7C0X9aYWqZqm4To7sDQ2zZFxmmARutY64OdQxb5QcnmC1EWkDc2owN3EPb-HJBOWKDoC5-peccN14pQ_NrWGXYXsvLCfSdxUj8SsGrIP3bTCtiAt-KbaIkoT4x625I84euYiClirO5szpsZigJqpswvmgoRJTfCmDx4OJEzdYcZmBPwbyxQk0Un3h-ZgaN29zgxYNWMjhMeLaew14lasBXafG9SkwQpDqwO-e_R9BAHInrqajI8zug77zQ9LNTAKgUzVlGi_l9fjr0w9jZYeW0Zi6hBWVZivEUR7PCRHL3szEsSHYfrZfWt3_iwXa9BpzJDrNsizRkrIppIa1mcwNnV8X2tJc-DXCzZaXybMXemPensxEdEt1AgHdC6E1aX_XTcedh5S3Q5dBKdwKARZqYmDL81ZFbSDi8-FbyMNU6eQLwBWff6XtuYfaRBSiZRZkrc22Sp9I12BivBeOptY8TKuNrMwoC7lfifIzi963MP9kTHhJDu8VVlMDTvI33SuiTVpKPXudjtR_4VndruljyJ4RebYXkbY98sp6ZByVYigRcK_bTdVV4O5oEfDVZdjqaop8rcghqCZdpJfU9xHLCBYB90559PekstP6K1ny75VHzSmXdjQP4nJuxct1XGc3k7jf2591_BxN1lee40B9gy2BmBYhY7pnkc4f5YsJ1iXyktvyNLLRKwGggb5SoS-uE5amldAeOMcCBCvHuJWfjLCNTQ8QOk1uK_PnuOk2Vt6mRQZr_GymiEBLRqj94sGeRg4GT_d6isDGEI-o45zKGNfUTY-XJToNLBt5ZCMB5lJ2jeOjKvrK0I" target="_blank">
                <img src="image/mt.png" style="width:85%"/>
            </a>
        </div>
        <div style="text-align:center">
            <img class="img_load" src="image/load.png"/>
            <span style="display:block;">加载中</span>
            <span style="display:block;">首次加载比较缓慢，请耐心等待</span>
            
        </div>
        
    </div>
  
    <div class="game" style="display:none">
      <video onloadedmetadata="onPlay(this)" id="inputVideo" autoplay muted playsinline></video>
      <!--<video src="image/bbt.mp4" id="inputVideo" autoplay muted playsinline></video>-->
      <canvas id="overlay"></canvas>
      
      <div class="hongbao">
          <a href="https://mp.weixin.qq.com/s?__biz=MzA3NzE5MjEzNw==&mid=2453281733&idx=1&sn=4ae614498608060bbbf56617ac0fa800&chksm=889b7563bfecfc7553e44fdb47e214a5ca52fdd5d0e5568ae449cdb9776632386dea352b32cc#rd" target="_blank">
                <img src="image/hb.png" style="width:75px"/>
            </a>
      </div>
      
      <div class="play">
          <div class="play_start">开始</div>
      </div>
      <div class="ballBg">
          <img id="ballImg" src="image/2.png"/>
      </div>
      <div class="bombTotal">
          <div class="totalNum">0</div>
      </div>
      <div class="limitTime">
          <div class="leftTime">10:00</div>
      </div>
        
        <div class="play_end">
            <div class="result">
                <div class="title">荣誉称号</div>
                <div class="main">
                    <img src="image/g2.png" style="width:120px;height:85px;margin-top:10px;"/>
                    <div class="play_end_head">吹牛小将</div>
                    <div class="content">
                        你吹破了<span class="total">0</span>只气球
                    </div>
                </div>
            </div>
            
        </div>
    </div>
    
    
    
    <!-- tiny_face_detector_controls -->
    <img src="image/1.png" style="display:none;" id="img1"/>
    <img src="image/2.png" style="display:none;" id="img2"/>
    <img src="image/3.png" style="display:none;" id="img3"/>
    <img src="image/4.png" style="display:none;" id="img4"/>
    <img src="image/5.png" style="display:none;" id="img5"/>
    <img src="image/6.png" style="display:none;" id="img6"/>
    <img src="image/7.png" style="display:none;" id="img7"/>
    <img src="image/8.png" style="display:none;" id="img8"/>
    <img src="image/9.png" style="display:none;" id="img9"/>
    <img src="image/10.png" style="display:none;" id="img10"/>
    <img src="image/11.png" style="display:none;" id="img11"/>
    <img src="image/12.png" style="display:none;" id="img12"/>
    <audio src="bgm.mp3" id="bgmAudio" controls="controls" autoplay="autoplay" loop="true" hidden="true"></audio>
    <audio src="go.mp3" id="myaudio" controls="controls" loop="false" hidden="true"></audio>
    <audio src="bomb.mp3" id="bombAudio" controls="controls" loop="false" hidden="true"></audio>
  </body>
  <script src="https://res2.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript"></script>
  <script>
    let forwardTimes = []
    let withBoxes = false
    let last_dist = 0;
    let ballWidth = 50;
    let ballHeight = 50;
    let bomb = 300;
    let addNum =5;
    let nowAdd =0;
    let timer;
    let faceResult;
    let imgNUM = 1;
    let imgID = 'img1';
    let total = 0;
    let limitTime = 10000;//毫秒
    let leftTime = 10000;//毫秒
    let play = false;
    let timing = 3;
    let timingGO;
    let loadBallBg =true;
    let leftTimer;
    let loadFirst =true;
    let canPlay = true;
    function onChangeHideBoundingBoxes(e) {
      withBoxes = !$(e.target).prop('checked')
    }

    function updateTimeStats(timeInMs) {
      forwardTimes = [timeInMs].concat(forwardTimes).slice(0, 30)
      const avgTimeInMs = forwardTimes.reduce((total, t) => total + t) / forwardTimes.length
      $('#time').val(`${Math.round(avgTimeInMs)} ms`)
      $('#fps').val(`${faceapi.utils.round(1000 / avgTimeInMs)}`)
    }

    async function onPlay() {
      $('.loading_box').hide();
      $('.game').show();
      const videoEl = $('#inputVideo').get(0)

      if(videoEl.paused || videoEl.ended || !isFaceDetectionModelLoaded())
        return setTimeout(() => onPlay())

      if(loadFirst){
          var width = document.body.clientWidth;
          var height = document.body.clientHeight;
          var video = $('#inputVideo');
          var video_width = video.width();
          loadFirst = false;
          var move_left = (video_width - width)/2;
          $('#inputVideo').attr("style","margin-left:"+(-move_left)+'px');
          $('#overlay').attr("style","margin-left:"+(-move_left)+'px');
          
      }
      const options = getFaceDetectorOptions()

      const ts = Date.now()

      const result = await faceapi.detectSingleFace(videoEl, options).withFaceLandmarks()
      
      faceResult = result;
      
      //updateTimeStats(Date.now() - ts)
      
      
      if(play){
          if (result) {
                const canvas = $('#overlay').get(0)
                const dims = faceapi.matchDimensions(canvas, videoEl, true)
                const resizedResult = faceapi.resizeResults(result, dims)
        
                if (withBoxes) {
                  faceapi.draw.drawDetections(canvas, resizedResult)
                }
                //faceapi.draw.drawFaceLandmarks(canvas, resizedResult)
                if(result.landmarks){
                    const dist = faceapi.euclideanDistance([result.landmarks.positions[62]['_x'], result.landmarks.positions[62]['_y']], [result.landmarks.positions[66]['_x'], result.landmarks.positions[66]['_y']])
                
                    if(last_dist > 25 && dist < 19 && nowAdd == 0){
                    	timer = setInterval(function(){ blowBall() }, 0.1);
                    }
                    if(dist > 22 && ballWidth > 50){
                    	//clearInterval(timer);
                    	//subTimer = setInterval(function(){ subBall(result) }, 2);
                    }
                    /*
                    if(last_dist <20 && dist > 22 && nowAdd > 0 ){
                    	clearInterval(timer);
                    }
                    */
                    last_dist = dist;
                    
                    if(ballWidth > bomb){
                        bombAudio()
                    	clearInterval(timer);
                    	ballWidth = 50;
                    	ballHeight = 50;
                    	nowAdd = 0;
                    	imgNUM ++;
                    	if(imgNUM >12){
                    	    imgNUM = 1;
                    	}
                    	imgID = 'img'+imgNUM;
                    	var src = $("#img"+(imgNUM+1)).attr('src')
                    	$('#ballImg').attr('src',src)
                    	total ++;
                    	$('.totalNum').text(total)
                    }
                    
                    if(nowAdd == 0){
                    	var c = document.getElementById('overlay');
                    	var ctx=c.getContext("2d");
                    	var img=document.getElementById(imgID);
                    	var height = $('#overlay').height();
                        ctx.drawImage(img,result.landmarks.positions[66]['_x']-(ballWidth/2),result.landmarks.positions[66]['_y'],ballWidth,ballHeight);
                    }
                }
                
            }
      
      }

      setTimeout(() => onPlay())
    }
    $('.play_start').click(function(){
        if(!canPlay){
            return;
        }
        canPlay = false;
        timing = 3;
        $('.play_end').hide();
        loadEndAudio();
        setTimeout(function(){
            console.log('ready go!')
            readyGoAudio();
        },4000)
        setTimeout(function(){
            play = true;
            
            leftTimer = setInterval(function(){limitTimeFun()},10);
            $('.play_start').hide();
            $('.ballBg').show();
            $('.bombTotal').show();
            $('.limitTime').show();
            canPlay = true;
            clearInterval(timingGO)
        },5000)
        
        timingGO = setInterval(function(){ 
            if(timing >= 0){
                if(timing == 0){
                    $('.play_start').text('GO')
                }else{
                    $('.play_start').text(timing)
                }
                if(timing >0)
                    timing--;
            }
            
        }, 1000);
    }
    )
    async function run() {
      // load face detection and face landmark models
      await changeFaceDetector(TINY_FACE_DETECTOR)
      await faceapi.loadFaceLandmarkModel('/')
      changeInputSize(224)

      // try to access users webcam and stream the images
      // to the video element
      const stream = await navigator.mediaDevices.getUserMedia({ video: {} })
      const videoEl = $('#inputVideo').get(0)
      videoEl.srcObject = stream
    }

    function updateResults() {}
    
    function limitTimeFun(){
        leftTime = leftTime - 10;
        var h = parseInt(leftTime/1000);
        if(h<10){
            h = "0"+h;
        }
        var l = (leftTime%1000).toFixed(0);
        var s = ((l/1000)*100).toFixed(0)
        if(s<10){
            s = "0"+s;
        }
        var t = h+':'+s;
        $('.leftTime').text(t);
        if(leftTime == 0){
            leftTime = limitTime;
            clearInterval(leftTimer);
            clearInterval(timer);
            play = false;
            var c = document.getElementById('overlay');
        	var ctx=c.getContext("2d");
            ctx.clearRect(0,0,c.width,c.height);
            $('.play_end .total').text(total);
            score(total);
            total = nowAdd = 0;
            $('.totalNum').text(total)
            $('.play_start').text('开始')
            $('.play_start').fadeIn();
            $('.play_end').fadeIn();
            screenShot();
        }
        
    }
    
    function score(n){
        var t = "吹牛小将";
        if(n > 8){
            t = "吹牛达人";
        }
        if(n < 5){
            t = "吹牛新手";
        }
        $('.play_end_head').text(t);
    }
    function screenShot(){
        html2canvas($(".game"), { 
          onrendered: function(canvas) { 
            //把截取到的图片替换到a标签的路径下载 
            //$("#download").attr('href',canvas.toDataURL()); 
            //下载下来的图片名字 
            //$("#download").attr('download',new Date().getTime() + ".png"); 
            //展示图片
            document.body.appendChild(canvas); 
          } 
        }); 
    }
    function drawBall(){
        var c = document.getElementById('overlay');
    	var ctx=c.getContext("2d");
    	var img=document.getElementById(imgID);
        ctx.drawImage(img,0,height,50,50);
    }
    
    
    function drawBallBg(ctx,height,img){
        if(loadBallBg){
            strokeRoundRect(ctx, 5, height - 165, 90, 90, 10);  
            fillRoundRect(ctx, 5,height - 165, 90, 90, 10, 'rgba(0,0,0,0.7)');
            ctx.drawImage(img,20,height - 150,50,50);
            loadBallBg = false;
        }
        
    }
    function blowBall(){
        if(faceResult.landmarks){
            var c = document.getElementById('overlay');
        	var height = $('#overlay').height();
        	var ctx=c.getContext("2d");
        	var img=document.getElementById(imgID);
            ctx.drawImage(img,faceResult.landmarks.positions[66]['_x']-(ballWidth/2),faceResult.landmarks.positions[66]['_y'],ballWidth,ballHeight);
        	ballWidth  = ballWidth+addNum;
        	ballHeight = ballHeight+addNum;
        	nowAdd = nowAdd + addNum;
        }
    	
    }
    
    
    function subBall(){
        var c = document.getElementById('overlay');
    	var height = $('#overlay').height();
    	var ctx=c.getContext("2d");
    	var img=document.getElementById(imgID);
        ctx.drawImage(img,faceResult.landmarks.positions[66]['_x']-(ballWidth/2),faceResult.landmarks.positions[66]['_y'],ballWidth,ballHeight);
    	ballWidth  = ballWidth-addNum;
    	ballHeight = ballHeight-addNum;
    	nowAdd = nowAdd - addNum;
    	if(nowAdd < 0){
    	    nowAdd = 0;
    	    clearInterval(subTimer);
    	}
    }
    
    function readyGoAudio() {
        var myAuto = document.getElementById('myaudio');
        myAuto.play();
    }
    
    function bombAudio(){
        console.log('吹爆了')
        var bomb = document.getElementById('bombAudio');
        bomb.currentTime = 0;bomb.volume = 0.8;
        bomb.play();
    }
    
    function loadEndAudio(){
        console.log('播放背景音乐')
        var bgm = document.getElementById('bgmAudio');
        bgm.volume = 0.3;
        bgm.play();
    }
    
    /**该方法用来绘制一个有填充色的圆角矩形 
     *@param cxt:canvas的上下文环境 
     *@param x:左上角x轴坐标 
     *@param y:左上角y轴坐标 
     *@param width:矩形的宽度 
     *@param height:矩形的高度 
     *@param radius:圆的半径 
     *@param fillColor:填充颜色 
     **/
    function fillRoundRect(cxt, x, y, width, height, radius, /*optional*/ fillColor) {
        //圆的直径必然要小于矩形的宽高          
        if (2 * radius > width || 2 * radius > height) { return false; }

        cxt.save();
        cxt.translate(x, y);
        //绘制圆角矩形的各个边  
        drawRoundRectPath(cxt, width, height, radius);
        cxt.fillStyle = fillColor || "#000"; //若是给定了值就用给定的值否则给予默认值  
        cxt.fill();
        cxt.restore();
    }


    /**该方法用来绘制圆角矩形 
     *@param cxt:canvas的上下文环境 
     *@param x:左上角x轴坐标 
     *@param y:左上角y轴坐标 
     *@param width:矩形的宽度 
     *@param height:矩形的高度 
     *@param radius:圆的半径 
     *@param lineWidth:线条粗细 
     *@param strokeColor:线条颜色 
     **/
    function strokeRoundRect(cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
        //圆的直径必然要小于矩形的宽高          
        if (2 * radius > width || 2 * radius > height) { return false; }

        cxt.save();
        cxt.translate(x, y);
        //绘制圆角矩形的各个边  
        drawRoundRectPath(cxt, width, height, radius);
        cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2  
        cxt.strokeStyle = strokeColor || "#000";
        cxt.stroke();
        cxt.restore();
    }

    function drawRoundRectPath(cxt, width, height, radius) {
        cxt.beginPath(0);
        //从右下角顺时针绘制，弧度从0到1/2PI  
        cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

        //矩形下边线  
        cxt.lineTo(radius, height);

        //左下角圆弧，弧度从1/2PI到PI  
        cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

        //矩形左边线  
        cxt.lineTo(0, radius);

        //左上角圆弧，弧度从PI到3/2PI  
        cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

        //上边线  
        cxt.lineTo(width - radius, 0);

        //右上角圆弧  
        cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

        //右边线  
        cxt.lineTo(width, height - radius);
        cxt.closePath();
    }
    
    $(document).ready(function() {
      //renderNavBar('#navbar', 'webcam_face_landmark_detection')
      loadEndAudio();
      initFaceDetectionControls()
      run()
      setTimeout(function(){
          
        if($('.loading_box').is(':visible')){
            console.log('长时间未加载完成，刷新！')
            window.location.reload();
        }
      
          
      },120000)
    })
	wx.ready(function(){
	    console.log('微信内播放音乐')
	    loadEndAudio();
	})
    
  </script>
  <script type="text/javascript" src="//js.users.51.la/21202603.js"></script>
</body>
</html>